<template>
  <div>
    <div v-loading="loading" class="grade" element-loading-text="加载中...">
      <div class="header flex-justify-between">
        <div class="btns flex-align-center">
          <button class="btn btn-bg2 mr5" @click="addGrade">
            <span class="iconfont icon-xinjian mr5"></span>添加级别</button
          >
          <el-dropdown trigger="click">
            <el-button
              class="btn btn-bg5 mr5 btn-change"
              :style="selecttion.length == 0 ? 'border: 1px solid #ccc;color:#999' : ''"
              :disabled="selecttion.length == 0"
            >
              <img :src="batch" class="mr5" alt="" sizes="16" srcset="" />批量操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="changeAll(1)"
                  ><el-icon><CircleCheck /></el-icon>批量启用</el-dropdown-item
                >
                <el-dropdown-item @click="changeAll(2)"
                  ><el-icon><Warning /></el-icon>批量禁用</el-dropdown-item
                >
                <el-dropdown-item @click="changeAll(3)"
                  ><el-icon><Delete /></el-icon>批量删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search flex-align-center">
          <el-input
            v-model.trim="name"
            placeholder="级别名称"
            class="input-width"
            clearable
            @keyup.enter.native="getList"
            @clear="getList"
          />
          <button class="btn btn-bg1 mr5" @click="getList">
            <el-icon class="mr5"><Search /></el-icon>搜索
          </button>
        </div>
      </div>
      <div class="table-grade">
        <el-table
          ref="tableDom"
          border
          stripe
          resizable
          :data="tableData"
          height="71vh"
          @selection-change="handleChange"
        >
          <el-table-column type="selection" width="40" fixed />
          <el-table-column show-overflow-tooltip prop="name" label="级别名称" min-width="150" />
          <el-table-column show-overflow-tooltip prop="name" label="状态" width="70">
            <template #default="scope">
              <el-tag v-if="scope.row.status" type="info">禁用</el-tag>
              <el-tag v-else type="success">启用</el-tag>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />

          <el-table-column fixed="right" label="操作" width="60">
            <template #default="scope">
              <div class="btns">
                <button class="btn-table bgColor2" @click="editGrade(scope.row.id)">详细</button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="footer flex-justify-end">
        <Pagination
          ref="pagination"
          :list_total="total"
          @size-change="getList"
          @current-change="getList"
        />
      </div>

      <!-- 添加/编辑  级别弹窗 -->
      <el-dialog
        v-model="addDialog"
        width="350px"
        :draggable="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
        class="add-dialog"
        top="8vh"
      >
        <template #header>
          <div class="my-header">
            <h3 class="title">{{ formTitle }}</h3>
          </div>
        </template>
        <div v-loading="formLoading">
          <div class="form-text">
            <el-form ref="formRef" label-width="70" :rules="rules" :model="form">
              <el-form-item label="级别名称" class="form-item" prop="name">
                <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
              </el-form-item>
              <el-form-item label="级别状态" class="form-item">
                <el-radio-group v-model="form.status">
                  <el-radio :value="false">
                    <span class="bg_text">启用</span>
                  </el-radio>
                  <el-radio :value="true">
                    <span class="bg_text">禁用</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
          <div :class="formTitle == '编辑级别' ? 'flex-justify-between' : 'flex-justify-end'">
            <el-button
              v-show="formTitle == '编辑级别'"
              color="#f56c6c"
              class="btn_delete"
              @click="changeAll(33)"
              >删除</el-button
            >
            <div class="right">
              <el-button class="btn_cancel" @click="addDialog = false"> 取消 </el-button>
              <el-button color="#007cff" class="btn_save" @click="saveData(formRef)"
                >保存</el-button
              >
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '../../../../../../../components/Pagination/index.vue'
  import batch from '@/assets/image/batch.png'
  import { ref, reactive, onMounted, markRaw } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Delete, Warning } from '@element-plus/icons-vue'
  import {
    getLevelList,
    saveLevel,
    getLevelDetail,
    disableLevel,
    deleteLevel,
  } from '../../../../../../../api/basic'

  const name = ref('') // 级别名称

  const tableData = ref([]) // 列表数据
  const tableDom = ref() // 列表dom

  const pagination = ref() // 分页dom
  const total = ref() // 总数目

  const addDialog = ref(false)
  const loading = ref(false)

  const formTitle = ref('')
  const formLoading = ref(false)

  const form = reactive({
    id: null,
    name: '',
    status: false,
  })

  // 表单元素
  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入级别名称', trigger: 'blur' }],
  })

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any[]) => {
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取分页数据
  const getPageData = () => {
    return {
      limit: pagination.value.size,
      name: name.value,
      page: pagination.value.current,
    }
  }

  // 获取列表数据
  const getList = async () => {
    loading.value = true
    await getLevelList(getPageData()).then((res) => {
      tableData.value = res.data.data.rows
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 添加级别
  const addGrade = () => {
    formTitle.value = '添加级别'
    form.id = null
    form.name = ''
    form.status = false
    addDialog.value = true
  }

  // 编辑级别
  const editGrade = async (id) => {
    addDialog.value = true
    formTitle.value = '编辑级别'
    formLoading.value = true
    await getLevelDetail(id).then((res) => {
      form.id = res.data.data.row.id
      form.name = res.data.data.row.name
      form.status = res.data.data.row.status
    })
    formLoading.value = false
  }

  // 保存方法
  const saveMethod = (method, data, dialog, load) => {
    load.value = true
    method(data).then((res) => {
      if (res.data.success == true) {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
        dialog.value = false
        load.value = false
        getList()
      } else {
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 2000,
        })
        load.value = false
        return
      }
    })
  }

  // 保存级别
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveMethod(saveLevel, form, addDialog, formLoading)
      }
    })
  }

  // 批量操作的方法
  const changeMethod = (type, method, arr, status, dialog) => {
    if (arr.length == 0) {
      ElMessage({
        message: `请选择要${type}的级别`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    ElMessageBox({
      type: type == '删除' ? 'error' : 'warning',
      title: '提示',
      icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
      message: `确认${type}选中的级别?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      if (status != 3) {
        await method(arr, status).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
        })
      } else {
        await method(arr).then((res: any) => {
          ElMessage({
            message: res.data.message,
            type: 'success',
            duration: 2000,
          })
          if (dialog != '') {
            dialog.value = false
          }
        })
      }
      tableDom.value.clearSelection()
      getList()
    })
  }

  // 修改级别状态
  const changeAll = (n) => {
    if (n == 1) {
      changeMethod('启用', disableLevel, selecttion.value, false, '')
    }
    if (n == 2) {
      changeMethod('禁用', disableLevel, selecttion.value, true, '')
    }
    if (n == 3) {
      changeMethod('删除', deleteLevel, selecttion.value, 3, '')
    }
    if (n == 33) {
      changeMethod('删除', deleteLevel, [form.id], 3, addDialog)
    }
  }

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
